package com.ebelter.bodyfatscale.ui.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import com.ebelter.bodyfatscale.util.DipUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by zcq
 */

public class ChartView extends View{

    private static final String TAG = "ChartView";

    public static final float WUXIAO_VALUE = Float.MIN_VALUE;

    private int greaterThanMaxVvalue = 30;
    private int lessThanMaxVvalue = 15;


    private float targetValue;
    private boolean displayTargetValue;

    public boolean isAnimation = true;
    public long animationTime=2000;//属性动画时间


    public void setTargetValue(float targetValue){
        this.targetValue=targetValue;
    }

    public void setDisplayTargetValue(boolean displayTargetValue){
        this.displayTargetValue=displayTargetValue;
    }




    public ChartView(Context context) {
        this(context,null);
    }
    public ChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setGreaterThanMaxVvalue(int greaterThanMaxVvalue){
        this.greaterThanMaxVvalue=greaterThanMaxVvalue;
    }

    public void setLessThanMaxVvalue(int lessThanMaxVvalue){
        this.lessThanMaxVvalue=lessThanMaxVvalue;
    }

    Paint mPaint;

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//抗锯齿
        lineWeight= dp2px(getContext(),2);
       // mPaint.setColor(getContext().getResources().getColor(R.color.bg_green));//这样获取颜色ok的
      //  mPaint.setColor(Color.parseColor("#232e40"));//这样获取颜色ok的
        mPaint.setStrokeWidth(lineWeight);
        setTextSize(6);
        mDashPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        mDashPaint.setStyle(Paint.Style.STROKE);
        mDashPaint.setColor(Color.parseColor("#fdc824"));
        mDashPaint.setStrokeWidth(dp2px(getContext(),1));
        mDashPaint.setPathEffect(new DashPathEffect(new float[] {5,5,5,5}, 1));
        mDashPaint.setTextSize(DipUtil.sp2px(getContext(),6));
       // mTargetPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        mDashPath=new Path();
    }

    public void setTextSize(int sp){
        textSize=DipUtil.sp2px(getContext(),sp);
        mPaint.setTextSize(textSize);
        textWidth1=getTextWidth(mPaint,"X");
        textWidth2=getTextWidth(mPaint,"XX");
        textWidth3=getTextWidth(mPaint,"XXX");
        textWidth4=getTextWidth(mPaint,"XXXX");
        textWidth5=getTextWidth(mPaint,"XXXXX");
    }

    int textWidth1;
    int textWidth2;
    int textWidth3;
    int textWidth4;
    int textWidth5;

    public int getTextWidth(Paint paint, String str) {
        int w= 0;
        if (str != null && str.length() > 0) {
            int len = str.length();
            float[] widths = new float[len];
            paint.getTextWidths(str, widths);
            for (int j = 0; j < len; j++) {
                w+= (int) Math.ceil(widths[j]);
            }
        }
        return w;
    }


    public int dp2px(Context context, float dipValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }



    ValueAnimator animator;
    public void show(){


        isShow=true;
        if (isAnimation){

            if (animator!=null){
                animator.cancel();
                animator=null;
            }

            animator = ValueAnimator.ofFloat(0.0f,1.0f);
            animator.setDuration(animationTime);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                   // ULog.i(TAG,"---onAnimationUpdate="+value);
                    if (landscapeValues2!=null&&landscapeValues!=null&&landscapeValues.size()>0){

                        for (int i=0;i<landscapeValues.size();i++){

                            if (landscapeValues2.size()>i){
                                landscapeValues2.set(i,landscapeValues.get(i)*value);
                            }

                        }
                    }
                    invalidate();

                }
            });
            animator.start();



        }else {
            landscapeValues2=landscapeValues;
            invalidate();
        }
    }


//    测量模式 	表示意思
//    UNSPECIFIED 	父容器没有对当前View有任何限制，当前View可以任意取尺寸
//    EXACTLY 	当前的尺寸就是当前View应该取的尺寸
//    AT_MOST 	当前尺寸是当前View能取的最大尺寸

   // match_parent—>EXACTLY。怎么理解呢？match_parent就是要利用父View给我们提供的所有剩余空间，
    // 而父View剩余空间是确定的，也就是这个测量模式的整数里面存放的尺寸。

   // wrap_content—>AT_MOST。怎么理解：就是我们想要将大小设置为包裹我们的view内容，那么尺寸大小就是父View给
    // 我们作为参考的尺寸，只要不超过这个尺寸就可以啦，具体尺寸就根据我们的需求去设定。

    //固定尺寸（如100dp）—>EXACTLY。用户自己指定了尺寸大小，我们就不用再去干涉了，当然是以指定的大小为主啦。


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
       // ULog.i(TAG,"onMeasure()---屏幕的宽："+ DipUtil.getWindowWidth(getContext())+"---屏幕的高："+DipUtil.getWindowHeight(getContext()));
        int width = getMySize(100, widthMeasureSpec);
        int height = getMySize(100, heightMeasureSpec);
       // ULog.i(TAG,"onMeasure()---控件的宽："+ width+"---控件的高："+height);
        setMeasuredDimension(width,height);
    }

    private int getMySize(int defaultSize, int measureSpec) {
        int mySize = defaultSize;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);//这里的的尺寸大小并不是最终我们的View的尺寸大小，而是父View提供的参考大小
        switch (mode) {
            case MeasureSpec.UNSPECIFIED: {//如果没有指定大小，就设置为默认大小
                mySize = defaultSize;
                break;
            }
            case MeasureSpec.AT_MOST: {//如果测量模式是最大取值为size
                //我们将大小取最大值,你也可以取其他值
                mySize = size;
                break;
            }
            case MeasureSpec.EXACTLY: {//如果是固定的大小，那就不要去改变它
                mySize = size;
                break;
            }
        }
        return mySize;
    }


    List<Float> landscapeValues;//横坐标的显示的值
    List<Float> landscapeValues2=new ArrayList<>();//横坐标的显示的值

    public void setLandscapeValues(List<Float> landscapeValues){
        this.landscapeValues=landscapeValues;
        if (this.landscapeValues2!=null){
            landscapeValues2.clear();
            this.landscapeValues2.addAll(landscapeValues);
        }

        if (this.landscapeValues!=null&&landscapeValues.size()>0){
            lineTopnMaxValue = Collections.max(this.landscapeValues)+greaterThanMaxVvalue;
            lineButtomnMinValue = Collections.min(this.landscapeValues)-lessThanMaxVvalue;

        }


    }
    List<String> landscapeTitles;//横坐标的显示的数据

    public void setLandscapeTitle(List<String> landscapeTitles){
        this.landscapeTitles=landscapeTitles;
    }



    int mWidth;
    int mHeight;

    int leftRightMagin;
    int itemWidth;
    int halfItemWidth;
    int lineHeight;
    int lineWeight;
    int textSize;
    float lineTopnMaxValue;
    float lineButtomnMinValue;

    boolean isShow;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mWidth=getMeasuredWidth();
        mHeight=getMeasuredHeight();
        lineHeight= (int) (mHeight*0.9);//0.9是看UI图比例计算出来的
        leftRightMagin= (int) (mWidth*0.03984);//0.03984是看UI图比例计算出来的
        if (getLandscapeValuesSize()==0){
            itemWidth=mWidth-2*leftRightMagin;
        }else {
            itemWidth=(mWidth-2*leftRightMagin)/getLandscapeValuesSize();
        }
        halfItemWidth=itemWidth/2;
       // ULog.i(TAG,"onDraw()---getMeasuredWidth()="+ mWidth+"---getMeasuredHeight="+mHeight+"---leftRightMagin="+leftRightMagin+"---itemWidth="+itemWidth+"---halfItemWidth="+halfItemWidth);
        if (!isShow){
            return;
        }
//        canvas.drawText("0,0",0,0,mPaint);
//        canvas.drawText("0,1",0,mHeight,mPaint);
//        canvas.drawText("1,0",mWidth,0,mPaint);
//        canvas.drawText("1,1",mWidth,mHeight,mPaint);

        drawHachures(canvas);//阴影线

        drawSolidLine(canvas);//实线

        drawHengTitles(canvas);//横向标题栏

        drawTargetValue(canvas);//画目标线



        //canvas.drawLine(10,10,300,300,mPaint);
    }

    private Paint mDashPaint;
  //  private Paint mTargetPaint;
    private Path mDashPath;
    //绘制目标值
    private void drawTargetValue(Canvas canvas) {
        if (displayTargetValue){
            float temp=((targetValue-lineButtomnMinValue)/(lineTopnMaxValue-lineButtomnMinValue));
            if (temp<0){
                temp=0;
            }
            int stopY2= (int) (lineHeight*(1-temp));
            mDashPath.reset();
            mDashPath.moveTo(leftRightMagin+halfItemWidth,stopY2);
            mDashPath.lineTo(mWidth-leftRightMagin,stopY2);
            canvas.drawPath(mDashPath,mDashPaint);

            mPaint.setColor(Color.parseColor("#fdc824"));
            String tar=targetValue+"";
            if (temp<0.5){
                stopY2=stopY2-textWidth2;
            }else {
                stopY2=stopY2+textWidth2;
            }

            canvas.drawText(tar,mWidth-leftRightMagin-getTextWidth(tar),stopY2,mPaint);
        }

    }

    public int hengTitleJiange=1;

    public void setHengTitleJiange(int jiange){
        if (jiange<=0){
            jiange=1;
        }
        this.hengTitleJiange=jiange;
    }

    private void drawHengTitles(Canvas canvas) {
        mPaint.setColor(Color.parseColor("#ffffff"));// 白色

        if (landscapeTitles!=null){
            for (int i=0;i<landscapeTitles.size();i++){
                if (i%hengTitleJiange==0){
                    String title=landscapeTitles.get(i);
                    int startX2=leftRightMagin+(i*itemWidth)+halfItemWidth;
                    startX2 = startX2-(getTextWidth(title)/2);
                    canvas.drawText(title,startX2,mHeight,mPaint);
                }

            }
        }

    }

    private int getTextWidth(String string){
        if (TextUtils.isEmpty(string)){
            return 0;
        }
        switch (string.length()){
            case 1:
                return textWidth1;

            case 2:
                return textWidth2;

            case 3:
                return textWidth3;

            case 4:
                return textWidth4;

            case 5:
                return textWidth5;

            default:
                    return textWidth1*string.length();
        }
    }

    //画值的实线
    private void drawSolidLine(Canvas canvas) {
        mPaint.setColor(Color.parseColor("#0158db"));//深蓝色

        if (landscapeValues!=null&&landscapeValues2!=null&&landscapeValues2.size()>0){
            for (int i=0;i<landscapeValues2.size();i++){

                float itemValue=landscapeValues2.get(i);

                int startX2=leftRightMagin+(i*itemWidth)+halfItemWidth;
                float temp=((itemValue-lineButtomnMinValue)/(lineTopnMaxValue-lineButtomnMinValue));
                if (temp<0){
                    temp=0;
                }

                float itemValue0 = 0;
                if (landscapeValues.size()>i){
                    itemValue0=landscapeValues.get(i);
                }
                
                
                int stopY2= (int) (lineHeight*(1-temp));
                if (WUXIAO_VALUE==itemValue0){
                    stopY2=lineHeight;
                }
                canvas.drawLine(startX2,lineHeight,startX2,stopY2,mPaint);
               // ULog.i(TAG,"画第i="+i+"线,---是否是无效值："+(WUXIAO_VALUE==itemValue)+"--startX="+startX2+"--startY="+lineHeight+"---stopX="+startX2+"---stopY="+stopY2);
            }
        }




    }

    //画阴影线
    private void drawHachures(Canvas canvas) {
        mPaint.setColor(Color.parseColor("#232e40"));//这样获取颜色ok的 阴影线颜色
        if (getLandscapeValuesSize()>0){
            for (int i=0;i<getLandscapeValuesSize();i++){
                int startX=leftRightMagin+(i*itemWidth)+halfItemWidth;
                canvas.drawLine(startX,0,startX,lineHeight,mPaint);//阴影线
            }
        }
    }




    private int getLandscapeTitleSize(){
        return landscapeTitles==null?0:landscapeTitles.size();
    }
    private int getLandscapeValuesSize(){
        return landscapeValues==null?0:landscapeValues.size();
    }
}
